import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
} from 'vue';

import _ from 'lodash';

import { dom, useQuasar, Platform } from '@teld/q-components';
import EchartConfig, {
  chartOptions,
  vBindChartOpts as vBindChartOptsBase,
} from './echartConfig';
import Chart from 't/common/chart';
import ChartConfig from './ChartConfig';
import draggable from 't/third-party/vuedraggable';
import './ChartView.scss';
import TIcon from 't/basic/icon';
import TPopupProxy from 't/basic/popup-proxy';
import TBanner from 't/basic/banner';
import QInnerLoading from '@teld/q-components/InnerLoading';
import QResizeObserver from '@teld/q-components/ResizeObserver';

import {
  commonProps,
  pickOwnForBasicComponent,
  usePropsTwoWayValues,
} from 't/common/utils';

export default defineComponent({
  props: {
    terms: Object,
    loading: {
      type: Boolean,
      default() {
        return false;
      },
    },
    chartList: {
      type: Array,
      default() {
        return [
          {
            ChartName: '按照 问题类别 统计',
            ChartType: 'fas-bar-chart',
            GroupColumn: 'CreatorName',
            Aggregation: 'count',
            AggregationFiled: '',
            SortType: 'value',
            DataSort: '',
            AggDateValue: '',
            visible: false,
          },
          {
            ChartName: '按照 问题类别2 统计',
            ChartType: 'fas-line-chart',
            GroupColumn: 'CreatorName',
            Aggregation: 'count',
            AggregationFiled: '',
            SortType: 'value',
            DataSort: '',
            AggDateValue: '',
            visible: false,
          },
        ];
      },
    },
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    columns: Array,
    chartFullHeight: {
      type: Number,
      default() {
        return null;
      },
    },
  },
  emits: ['update:chartList', 'updateAdvQuery', 'addchart', 'fullChart'],

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();
    const Term = props.terms;
    const { chartList, ...twoWayProps } = usePropsTwoWayValues(['chartList']);
    // let chartList = twoWayProps.chartList;

    const vBindChartOpts = conf => {
      return { ...vBindChartOptsBase(conf), data: props.data };
    };

    const drag = ref(false);
    const defaultChartHeight = '409px';
    const chartHeight = ref(defaultChartHeight);
    const slotItemStyle = index => {
      if (fullChart.value === index || false === fullChart.value) {
        return {};
      } else {
        return { display: 'none' };
      }
    };
    const slotItem = (item, index) => (
      <div
        ref={el => (refCommChartDiv.value[index] = el)}
        class='col-sm-12 col-sm-6 col-md-6 col-lg-3'
        style={{ height: chartHeight.value, ...slotItemStyle(index) }}
      >
        <div
          // ref="'chartC'+index"
          class='bg-grey-2 chartCol column'
          style='border-radius: 7.5px; padding: 30px; padding-top:0px; height: 100%;'
        >
          <div class='draggable row justify-center items-center'>
            <div class='col-auto'>
              <TIcon name='more_horiz' class='drag-widget-chart' />
            </div>
          </div>
          <div class='row justify-between items-center'>
            <div class='col chartTitle'>{item.ChartName}</div>
            <div class='col-auto'>
              <div class='row q-gutter-md'>
                <TIcon
                  // size='sm'
                  name='fas dx-icon icon-t-fullscreen'
                  onClick={event => {
                    full(item, index, event);
                  }}
                />
                {/* <TIcon
                  // size='sm'
                  onClick={() => {
                    configChartInstanceIndex = index;
                    configChartInstance.value = { ...item };
                    // configChartInstance.value = item;
                    chartConfigDialog.value = true;
                  }}
                  name='more_horiz'
                /> */}
                <TIcon name='more_horiz'>
                  <TPopupProxy class="mv-chart-menu-popup" ref={chartPopupProxy}>
                    <div style='margin:8px 16px;'>
                      <div
                        class='row more_menuitem'
                        onKeydownEnter={() => {
                          configChartInstanceIndex = index;
                          configChartInstance.value = { ...item };
                          chartConfigDialog.value = true;
                        }}
                        onClick={() => {
                          configChartInstanceIndex = index;
                          configChartInstance.value = { ...item };
                          chartConfigDialog.value = true;
                          chartPopupProxy.value.hide();
                        }}
                      >
                        <div>
                          <TIcon name='fas dx-icon icon-t-edit' />
                        </div>
                        <div>{Term?.title?.edit}</div>
                      </div>
                      <div
                        class='row more_menuitem'
                        onKeydownEnter={() => {
                          chartList.value.splice(index, 1);
                          emit('updateAdvQuery');
                        }}
                        onClick={() => {
                          chartList.value.splice(index, 1);
                          emit('updateAdvQuery');
                        }}
                      >
                        <div>
                          <TIcon name='fas dx-icon icon-t-delete-outlined' />
                        </div>
                        <div>{Term.button.delete}</div>
                      </div>
                    </div>
                    {/* <TBanner
                      class='more_menuitem'
                      onClick={() => {
                        configChartInstanceIndex = index;
                        configChartInstance.value = { ...item };
                        chartConfigDialog.value = true;
                      }}
                    >
                      {{
                        avatar() {
                          return <TIcon name='fas dx-icon icon-t-edit' />;
                        },
                        default() {
                          return Term.title.edit;
                        },
                      }}
                    </TBanner>
                    <TBanner
                      class='more_menuitem'
                      onClick={() => {
                        chartList.value.splice(index, 1);
                      }}
                    >
                      {{
                        avatar() {
                          return (
                            <TIcon name='fas dx-icon icon-t-delete-outlined' />
                          );
                        },
                        default() {
                          return Term.button.delete;
                        },
                      }}
                    </TBanner>*/}
                  </TPopupProxy>
                </TIcon>
              </div>
            </div>
          </div>
          <div class='col' style='overflow: hidden;'>
            <Chart
              enableNoDataPlaceholder={true}
              ref={el => (refCommChartInstances.value[index] = el)}
              III={index}
              height='100%'
              width='100%'
              {...vBindChartOpts(item)}
            />
          </div>
        </div>
      </div>
    );

    const onEnd = () => {
      // emit('update:chartList', chartList); /** 不需要更新了，否则会导致堆栈溢出 */
      emit('updateAdvQuery');
    };

    const getCommChartInstanceByIndex = index => {
      return _.find(refCommChartInstances.value, item => {
        return item.$attrs.III == index;
      });
    };

    const fullChart = ref(false);
    const full = (conf, confIndex, event) => {
      // let winHeight = $(document).height();
      // let offsetTop = $(this.$refs.refChartRow.$el).offset().top;
      const { height, offset } = dom;
      let winHeight = document.documentElement.clientHeight; //dom.height(document.documentElement);/** 用quars的这个方法，在线上运行时获取高度不对 */
      let offsetTop = offset(refChartRow.value).top;
      let fullHeight = winHeight - offsetTop;
      let chartInstance = getCommChartInstanceByIndex(confIndex);
      if (chartInstance) {
        let echartDow = chartInstance.currentEchart.getDom();
        if (event.srcElement.classList.contains('icon-t-fullscreen')) {
          event.srcElement.classList.remove('icon-t-fullscreen');
          event.srcElement.classList.add('icon-t-fullscreen-exit');
          // echartDow.style.height = fullHeight - 100 + 'px';
          fullChart.value = confIndex;
        } else {
          event.srcElement.classList.remove('icon-t-fullscreen-exit');
          event.srcElement.classList.add('icon-t-fullscreen');
          // echartDow.style.height = '300px';
          fullChart.value = false;
        }
      }

      let jq = refCommChartDiv.value[confIndex];
      jq.classList.toggle('full');
      let isFull = jq.classList.contains('full');
      if (props.chartFullHeight) {
        fullHeight = props.chartFullHeight;
      }
      emit('fullChart', isFull);
      if (isFull) {
        // jq.style.height = `${parseInt(fullHeight) - 30}px`;
        chartHeight.value = `${parseInt(fullHeight) - 30}px`;
        // setTimeout(() => {
        //   chartInstance.resize();
        // }, 1000);
        // jq.css('height', parseInt(fullHeight) - 20);
      } else {
        // setTimeout(() => {
        //   chartInstance.resize();
        // }, 1000);
        // jq.css('height', '');
        // jq.style.height = '409px';
        chartHeight.value = defaultChartHeight;

        setTimeout(() => {
          refCommChartInstances.value?.forEach(item => { item?.currentEchart?.resize() })
        }, 100);
      }
    };

    const chartPopupProxy = ref();
    const chartConfigDialog = ref(false);
    const configChartInstance = ref();
    let configChartInstanceIndex = 0;
    const refChartRow = ref();
    const refCommChartInstances = ref([]);
    const refCommChartDiv = ref([]);

    const onResize = () => {
      refCommChartInstances.value?.forEach(item => {
        item?.currentEchart?.resize();
      });
    }

    return () => {
      return (
        <>
          {/* <div>props.chartList{props.chartList.length}/{chartList.value.length}</div> */}
          <div ref={refChartRow}>
            {chartConfigDialog.value && (
              <ChartConfig
                terms={Term}
                instance={configChartInstance.value}
                v-model:show={chartConfigDialog.value}
                columns={props.columns}
                chartList={chartList.value}
                data={props.data}
                onConfirm={e => {
                  // proxyThis.UpdateAdvQuery('ChartView');
                  // alert(222)
                  // configChartInstance.value = { ...e };
                  chartList.value[configChartInstanceIndex] = e;
                  emit('updateAdvQuery');
                }}
              ></ChartConfig>
            )}
            <draggable
              class='row q-col-gutter-sm q-pt-sm'
              v-model={chartList.value}
              group='people'
              onEnd={onEnd}
              item-key='id'
              handle='.drag-widget-chart'
            >
              {{
                item({ element, index }) {
                  return slotItem(element, index);
                },
              }}
            </draggable>

            {chartList.value.length == 0 && (
              <div class='row q-col-gutter-sm q-pt-sm'>
                <div
                  class='col-sm-12 col-sm-6 col-md-6 col-lg-3'
                  style={{ height: defaultChartHeight }}
                >
                  <div
                    // ref="'chartC'+index"
                    class='bg-grey-2 chartCol column items-center justify-center'
                    style='border-radius: 7.5px; padding: 30px; padding-top:0px; height: 100%;'
                  >
                    <div>
                      <TIcon
                        onClick={() => {
                          emit('addchart');
                        }}
                        name='addchart'
                        style={{
                          fontSize: '60px',
                          opacity: 0.5,
                          cursor: 'pointer',
                        }}
                      />
                    </div>
                  </div>
                </div>
              </div>
            )}
            <QInnerLoading class='chartLoading' showing={props.loading}></QInnerLoading>
            <QResizeObserver onResize={onResize} />
          </div>
        </>
      );
    };
  },
});
